import { getAppNav } from '@/App'
import CIcon from '@/components/CIcon/CIcon'
import IMenuVO from '@/model/vo/menu/IMenuVO'
import { useAppSelector } from '@/store'
import { Card, CardGroup, Typography } from '@douyinfe/semi-ui'
import { IconExternalOpen } from '@douyinfe/semi-icons'

export default function Workplace() {
  const userMenuListOrig = useAppSelector((state) => state.user.userMenuList)
  let userMenuList: IMenuVO[] = JSON.parse(JSON.stringify(userMenuListOrig))
  userMenuList = userMenuList.filter(
    (item) => item.path && !item.firstFlag && item.showFlag
  ) // 只要有 path值，不是 默认页面，显示 的菜单
  const linkMenuList = userMenuList.filter((item) => item.linkFlag) // 外链集合
  userMenuList = userMenuList.filter((item) => !item.linkFlag) // 不是外链的，拼接到前面
  userMenuList = userMenuList.concat(linkMenuList) // 把外链的，拼接到最后
  return (
    <>
      <CardGroup spacing={12} className="p-20">
        {userMenuList.map((item) => (
          <Card
            key={item.id}
            shadows="always"
            title={
              <div className="flex ai-c">
                <WorkplaceCardTitle
                  userMenuListOrig={userMenuListOrig}
                  item={item}
                />
              </div>
            }
            headerLine={false}
            style={{ width: 260 }}
            headerExtraContent={
              <Typography.Text
                link
                title={item.linkFlag ? '点击打开' : '点击前往'}
                onClick={() => {
                  if (item.linkFlag) {
                    window.open(item.path, '_blank')
                  } else {
                    getAppNav()(item.path)
                  }
                }}
                icon={item.linkFlag ? <IconExternalOpen /> : null}
              >
                {item.linkFlag ? 'Open' : 'Go'}
              </Typography.Text>
            }
          >
            <Typography.Text>{item.name}</Typography.Text>
          </Card>
        ))}
      </CardGroup>
    </>
  )
}

interface IWorkplaceCardTitle {
  userMenuListOrig: IMenuVO[]
  item: IMenuVO
}

function WorkplaceCardTitle(props: IWorkplaceCardTitle) {
  let iconStr = props.item.icon
  if (!iconStr) {
    props.userMenuListOrig.some((subItem) => {
      if (subItem.id === props.item.parentId) {
        iconStr = subItem.icon
        return true
      }
    })
  }
  return (
    <>
      <CIcon icon={iconStr} className="m-r-10" /> {props.item.name}
    </>
  )
}
